import hashlib
import json, datetime
import re
import time, os
import uuid

from django.db.models import Q
from django.shortcuts import render, HttpResponse, redirect
from django.views import View
# Create your views here.
from correspondence.models import InboxInfo, InboxInfoPeople, chatting_records, ChatGroups
from administrative.models import Topicsattachments
# 通信首页
from Administrative_office_system.utils.views import LoginRequiredMixin
from personal_center.models import User


class home(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
            position = request.user.post
            department = request.user.company.name
        except:
            return redirect("/")


        return render(request, 'correspondence/home.html',
                      {'realname': real_name, 'position': position, 'department': department})

# 收件箱
class inbox(LoginRequiredMixin, View):
    def get(self, request):
        try:
            real_name = request.user.real_name
            position = request.user.post
            department = request.user.company.name
        except:
            return redirect("/")

        page = request.GET.get("page", 1)  # 页码
        search = request.GET.get("search", None)            # 是否查询，是否翻页
        search_type = request.GET.get("search_type", 'all')            # 查询类型
        delete_list = request.GET.get("delete_list", None)              # 删除邮件列表
        search_data = request.GET.get("search_data", None)              # 按照时间查询
        search_value = request.GET.get("search_value", None)              # 按照值查询
        all_read = request.GET.get("all_read", None)              # 全部已读
        returnDict, messige_flag = {}, False
        message_id = request.GET.get("message_id", '')
        if message_id:
            messige_flag = True
            inbox_obj = InboxInfo.objects.get(id=message_id)
            inbox_li = []
            item = {}

            recipient = [obj.recipient_name for obj in inbox_obj.inboxinfopeople_set.all()]
            file_path_list = [{"file_path": str(i.file_path), "file_name": i.file_name, "pdf_path": i.pdf_path,
                               "download_path": f"/announcements/file_download?file_path={os.getcwd()}/media/{str(i.file_path)}" if ('static' not in str(i.file_path)) and ('media' not in str(i.file_path)) else f"/announcements/file_download?file_path={os.getcwd()}{str(i.file_path)}"}
                              for i in Topicsattachments.objects.filter(topics_number=inbox_obj.accessory_uuid)]

            item['message_id'] = inbox_obj.id
            item['sender_name'] = inbox_obj.proposer.real_name
            item['sender'] = inbox_obj.proposer.job_number
            item['recipient_name'] = recipient
            item['recipient'] = []
            item['title'] = inbox_obj.title
            item['message_content'] = inbox_obj.content.replace('%26nbsp;', '&nbsp;')
            item['create_time'] = inbox_obj.create_time.strftime("%Y-%m-%d %H:%M:%S")
            item['file_url'] = file_path_list
            # item['file_url'] = []
            inbox_li.append(item)

            # 更新状态为已读
            inbox_people_obj = request.user.inboxinfopeople_set.get(inbox_id=inbox_obj)
            inbox_people_obj.readed = "read"
            inbox_people_obj.save()

            message_data = {
                'realname': real_name, 'position': position, 'department': department,
                'mail_title': inbox_li[0]['title'],
                'recipient_name': inbox_li[0]['recipient_name'],
                'recipient': inbox_li[0]['recipient'],
                'message_content': inbox_li[0]['message_content'].replace('%26nbsp;', '&nbsp;'),
                'create_time': inbox_li[0]['create_time'],
                'sender_name': inbox_li[0]['sender_name'],
                'sender': inbox_li[0]['sender'],
                'file_url': inbox_li[0]['file_url'],
            }
            returnDict = {'code': 200, 'message': '获取成功', 'message_data': message_data}

        # 删除邮件
        if delete_list:
            InboxInfoPeople.objects.filter(id__in=json.loads(delete_list)).update(deleted='b')

        # 全部设为已读
        if all_read:
            request.user.inboxinfopeople_set.filter(deleted='a').update(readed='read')

        if search_type == "all":
            if search_data and not search_value:
                startTime = datetime.datetime.strptime(search_data.replace("/", '-'), '%Y-%m-%d')
                endTime = startTime + datetime.timedelta(days=1)
                inbox_obj = request.user.inboxinfopeople_set.filter(deleted='a', create_time__range=(startTime, endTime), inbox_id__is_draft=False).order_by("-create_time")

            elif search_value and not search_data:
                inbox_obj = request.user.inboxinfopeople_set.filter(Q(inbox_id__title__contains=search_value) | Q(inbox_id__plain_text__contains=search_value), deleted='a', inbox_id__is_draft=False).order_by("-create_time")

            elif search_value and search_data:
                startTime = datetime.datetime.strptime(search_data.replace("/", '-'), '%Y-%m-%d')
                endTime = startTime + datetime.timedelta(days=1)
                inbox_obj = request.user.inboxinfopeople_set.filter(Q(inbox_id__title__contains=search_value) | Q(inbox_id__plain_text__contains=search_value), deleted='a', create_time__range=(startTime, endTime), inbox_id__is_draft=False).order_by("-create_time")
            else:
                inbox_obj = request.user.inboxinfopeople_set.filter(deleted='a', inbox_id__is_draft=False).order_by("-create_time")

        elif search_type == "unread":
            inbox_obj = request.user.inboxinfopeople_set.filter(readed='unread', deleted='a', inbox_id__is_draft=False).order_by("-create_time")

        else:
            inbox_obj = request.user.inboxinfopeople_set.filter(readed='read', deleted='a', inbox_id__is_draft=False).order_by("-create_time")

        inbox_li = []
        for i in inbox_obj:
            item = {}
            item['message_id'] = i.inbox_id.id
            item['sender_name'] = i.inbox_id.proposer.real_name
            item['sender'] = i.inbox_id.proposer.job_number
            item['title'] = i.inbox_id.title
            item['read'] = False if i.readed == 'unread' else True
            item['content'] = i.inbox_id.content.replace("%26nbsp;", '')
            item['plain_text'] = i.inbox_id.plain_text
            item['create_time'] = i.inbox_id.create_time.strftime("%Y-%m-%d %H:%M")
            item['ids'] = str(uuid.uuid4())
            item['deleted_id'] = i.id
            inbox_li.append(item)

        page_number = inbox_obj.count()//15 if inbox_obj.count()%15 == 0 else (inbox_obj.count()//15)+1
        cunt_page = int(page)
        last_page = int(page)-1
        next_page = int(page)+1

        if search:
            returnDict = {'code': 200, 'message': '获取成功', 'data': {"inbox_li": inbox_li[(int(page) - 1) * 15:int(page) * 15], "page_number": page_number,
                       "cunt_page": cunt_page, "last_page": last_page, "next_page": next_page}}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")

        return render(request, 'correspondence/inbox.html',
                      {'realname': real_name, 'position': position, 'department': department, 'inbox_li': inbox_li[(int(page) - 1) * 15:int(page) * 15], "page_number": page_number,
                       "cunt_page": cunt_page, "last_page": last_page, "next_page": next_page, "returnDict": returnDict, "messige_flag": messige_flag})

# 收件详情
class InboxDetialView(LoginRequiredMixin, View):
    def get(self, request):
        message_id = request.GET.get("message_id", '')
        username = request.user.username
        real_name = request.user.real_name
        position = request.user.post
        department = request.user.company.name

        if not all([message_id, username]):
            returnDict = {"code": 400, "message": "error", "data": '缺少必传参数'}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")

        inbox_obj = InboxInfo.objects.get(id=message_id)
        inbox_li = []
        item = {}

        recipient = [obj.recipient_name for obj in inbox_obj.inboxinfopeople_set.all()]
        print("查询接收人员完毕！")
        file_path_list = [{"file_path": str(i.file_path), "file_name": i.file_name, "pdf_path": i.pdf_path,
                           "download_path": f"/announcements/file_download?file_path={os.getcwd()}/media/{str(i.file_path)}" if ('static' not in str(i.file_path)) and ('media' not in str(i.file_path)) else f"/announcements/file_download?file_path={os.getcwd()}{str(i.file_path)}"}
                          for i in Topicsattachments.objects.filter(topics_number=inbox_obj.accessory_uuid)]

        item['message_id'] = inbox_obj.id
        item['sender_name'] = inbox_obj.proposer.real_name
        item['sender'] = inbox_obj.proposer.job_number
        item['recipient_name'] = recipient
        item['recipient'] = []
        item['title'] = inbox_obj.title
        item['message_content'] = inbox_obj.content.replace('%26nbsp;', '&nbsp;')
        item['create_time'] = inbox_obj.create_time.strftime("%Y-%m-%d %H:%M:%S")
        item['file_url'] = file_path_list
        # item['file_url'] = []
        inbox_li.append(item)

        # 更新状态为已读
        inbox_people_obj = request.user.inboxinfopeople_set.get(inbox_id=inbox_obj)
        inbox_people_obj.readed="read"
        inbox_people_obj.save()

        message_data = {
            'realname': real_name, 'position': position, 'department': department,
            'mail_title': inbox_li[0]['title'],
            'recipient_name': inbox_li[0]['recipient_name'],
            'recipient': inbox_li[0]['recipient'],
            'message_content': inbox_li[0]['message_content'].replace('%26nbsp;', '&nbsp;'),
            'create_time': inbox_li[0]['create_time'],
            'sender_name': inbox_li[0]['sender_name'],
            'sender': inbox_li[0]['sender'],
            'file_url': inbox_li[0]['file_url'],
            'message_id': inbox_li[0]['message_id']
        }
        returnDict = {'code': 200, 'message': '获取成功', 'message_data': message_data}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

# 发件箱
class sent(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
            position = request.user.post
            department = request.user.company.name
        except:
            return redirect("/")

        page = request.GET.get("page", 1)  # 页码
        search = request.GET.get("search", None)  # 是否查询，是否翻页
        delete_list = request.GET.get("delete_list", None)  # 删除邮件列表
        search_data = request.GET.get("search_data", None)  # 按照时间查询
        search_value = request.GET.get("search_value", None)  # 按照值查询

        if delete_list:
            InboxInfo.objects.filter(id__in=json.loads(delete_list)).update(deleted='b')

        if search_data and not search_value:
            startTime = datetime.datetime.strptime(search_data.replace("/", '-'), '%Y-%m-%d')
            endTime = startTime + datetime.timedelta(days=1)
            inbox_obj = InboxInfo.objects.filter(proposer=request.user, deleted='a', create_time__range=(startTime, endTime), is_draft=False).order_by("-create_time")
            print(inbox_obj.count())

        elif search_value and not search_data:
            inbox_obj = InboxInfo.objects.filter(Q(title__contains=search_value) | Q(plain_text__contains=search_value), proposer=request.user, deleted='a', is_draft=False).order_by("-create_time")

        elif search_value and search_data:
            startTime = datetime.datetime.strptime(search_data.replace("/", '-'), '%Y-%m-%d')
            endTime = startTime + datetime.timedelta(days=1)
            inbox_obj = InboxInfo.objects.filter(Q(title__contains=search_value) | Q(plain_text__contains=search_value), proposer=request.user, deleted='a', create_time__range=(startTime, endTime), is_draft=False).order_by("-create_time")
        else:
            print("oik")
            inbox_obj = InboxInfo.objects.filter(proposer=request.user, deleted='a', is_draft=False).order_by("-create_time")

        inbox_li = []
        for i in inbox_obj:
            item = {}
            item['message_id'] = i.id
            item['sender_name'] = i.proposer.real_name
            item['sender'] = i.proposer.job_number
            item['title'] = i.title
            item['content'] = i.content.replace("%26nbsp;", '')
            item['plain_text'] = i.plain_text
            item['create_time'] = i.create_time.strftime("%Y-%m-%d %H:%M")
            item['ids'] = str(uuid.uuid4())
            item['deleted_id'] = i.id
            inbox_li.append(item)

        page_number = inbox_obj.count() // 15 if inbox_obj.count() % 15 == 0 else (inbox_obj.count() // 15) + 1
        cunt_page = int(page)
        last_page = int(page) - 1
        next_page = int(page) + 1

        if search:
            returnDict = {'code': 200, 'message': '获取成功',
                          'data': {"inbox_li": inbox_li[(int(page) - 1) * 15:int(page) * 15],
                                   "page_number": page_number,
                                   "cunt_page": cunt_page, "last_page": last_page, "next_page": next_page}}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")

        return render(request, 'correspondence/sent.html',
                      {'realname': real_name, 'position': position, 'department': department,
                       'inbox_li': inbox_li[(int(page) - 1) * 15:int(page) * 15], "page_number": page_number,
                       "cunt_page": cunt_page, "last_page": last_page, "next_page": next_page})

    def post(self, request):
        message_id = request.POST.get("message_id", '')
        real_name = request.user.real_name
        position = request.user.post
        department = request.user.company.name

        inbox_obj = InboxInfo.objects.get(id=message_id)
        inbox_li = []
        item = {}

        recipient = [obj.recipient_name for obj in inbox_obj.inboxinfopeople_set.all()]
        print("查询接收人员完毕！")
        file_path_list = [{"file_path": str(i.file_path), "file_name": i.file_name, "pdf_path": i.pdf_path,
                           "download_path": f"/announcements/file_download?file_path={os.getcwd()}/media/{str(i.file_path)}" if ('static' not in str(i.file_path)) and ('media' not in str(i.file_path)) else f"/announcements/file_download?file_path={os.getcwd()}{str(i.file_path)}"}
                          for i in Topicsattachments.objects.filter(topics_number=inbox_obj.accessory_uuid)]

        item['message_id'] = inbox_obj.id
        item['sender_name'] = inbox_obj.proposer.real_name
        item['sender'] = inbox_obj.proposer.job_number
        item['recipient_name'] = recipient
        item['recipient'] = []
        item['title'] = inbox_obj.title
        item['message_content'] = inbox_obj.content.replace('%26nbsp;', '&nbsp;')
        item['create_time'] = inbox_obj.create_time.strftime("%Y-%m-%d %H:%M:%S")
        item['file_url'] = file_path_list
        inbox_li.append(item)

        message_data = {
            'realname': real_name, 'position': position, 'department': department,
            'mail_title': inbox_li[0]['title'],
            'recipient_name': inbox_li[0]['recipient_name'],
            'recipient': inbox_li[0]['recipient'],
            'message_content': inbox_li[0]['message_content'].replace('%26nbsp;', '&nbsp;'),
            'create_time': inbox_li[0]['create_time'],
            'sender_name': inbox_li[0]['sender_name'],
            'sender': inbox_li[0]['sender'],
            'file_url': inbox_li[0]['file_url'],
        }
        returnDict = {'code': 200, 'message': '获取成功', 'message_data': message_data}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


# 草稿箱
class drafts(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
            position = request.user.post
            department = request.user.company.name
        except:
            return redirect("/")

        page = request.GET.get("page", 1)  # 页码
        search = request.GET.get("search", None)  # 是否查询，是否翻页
        delete_list = request.GET.get("delete_list", None)  # 删除邮件列表
        search_data = request.GET.get("search_data", None)  # 按照时间查询
        search_value = request.GET.get("search_value", None)  # 按照值查询

        if delete_list:
            InboxInfo.objects.filter(id__in=json.loads(delete_list)).update(deleted='b')
        inbox_obj = InboxInfo.objects.filter(proposer=request.user, deleted='a', is_draft=True)
        if search_value:
            inbox_obj = inbox_obj.filter(Q(title__contains=search_value) | Q(plain_text__contains=search_value))
        if search_data:
            startTime = datetime.datetime.strptime(search_data.replace("/", '-'), '%Y-%m-%d')
            endTime = startTime + datetime.timedelta(days=1)
            inbox_obj = inbox_obj.filter(create_time__range=(startTime, endTime))

        inbox_obj.order_by("-create_time")
        inbox_li = []
        for i in inbox_obj:
            item = {}
            item['message_id'] = i.id
            item['sender_name'] = i.proposer.real_name
            item['sender'] = i.proposer.job_number
            item['title'] = i.title
            item['content'] = i.content.replace("%26nbsp;", '')
            item['plain_text'] = i.plain_text
            item['create_time'] = i.create_time.strftime("%Y-%m-%d %H:%M")
            item['ids'] = str(uuid.uuid4())
            item['deleted_id'] = i.id
            inbox_li.append(item)

        page_number = inbox_obj.count() // 15 if inbox_obj.count() % 15 == 0 else (inbox_obj.count() // 15) + 1
        cunt_page = int(page)
        last_page = int(page) - 1
        next_page = int(page) + 1

        if search:
            returnDict = {'code': 200, 'message': '获取成功',
                          'data': {"inbox_li": inbox_li[(int(page) - 1) * 15:int(page) * 15],
                                   "page_number": page_number,
                                   "cunt_page": cunt_page, "last_page": last_page, "next_page": next_page}}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")

        return render(request, 'correspondence/drafts.html',
                      {'realname': real_name, 'position': position, 'department': department,
                       'inbox_li': inbox_li[(int(page) - 1) * 15:int(page) * 15], "page_number": page_number,
                       "cunt_page": cunt_page, "last_page": last_page, "next_page": next_page})

# 已删除
class deleted(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
            position = request.user.post
            department = request.user.company.name
        except:
            return redirect("/")

        page = request.GET.get("page", 1)  # 页码
        search = request.GET.get("search", None)  # 是否查询，是否翻页
        search_type = request.GET.get("search_type", 'all')  # 查询类型
        delete_list = request.GET.get("delete_list", None)  # 删除邮件列表
        search_data = request.GET.get("search_data", None)  # 按照时间查询
        search_value = request.GET.get("search_value", None)  # 按照值查询
        reduction_list = request.GET.get("reduction_list", None)           # 还原

        # 删除邮件
        if delete_list:
            InboxInfoPeople.objects.filter(id__in=json.loads(delete_list)).update(deleted='c')

        # 全部设为已读
        if reduction_list:
            request.user.inboxinfopeople_set.filter(id__in=json.loads(reduction_list)).update(deleted='a')

        if search_type == "all":
            if search_data and not search_value:
                startTime = datetime.datetime.strptime(search_data.replace("/", '-'), '%Y-%m-%d')
                endTime = startTime + datetime.timedelta(days=1)
                inbox_obj = request.user.inboxinfopeople_set.filter(deleted='b',
                                                                    create_time__range=(startTime, endTime),
                                                                    inbox_id__is_draft=False).order_by("-create_time")

            elif search_value and not search_data:
                inbox_obj = request.user.inboxinfopeople_set.filter(
                    Q(inbox_id__title__contains=search_value) | Q(inbox_id__plain_text__contains=search_value),
                    deleted='b', inbox_id__is_draft=False).order_by("-create_time")

            elif search_value and search_data:
                startTime = datetime.datetime.strptime(search_data.replace("/", '-'), '%Y-%m-%d')
                endTime = startTime + datetime.timedelta(days=1)
                inbox_obj = request.user.inboxinfopeople_set.filter(
                    Q(inbox_id__title__contains=search_value) | Q(inbox_id__plain_text__contains=search_value),
                    deleted='b', create_time__range=(startTime, endTime), inbox_id__is_draft=False).order_by(
                    "-create_time")
            else:
                inbox_obj = request.user.inboxinfopeople_set.filter(deleted='b', inbox_id__is_draft=False).order_by(
                    "-create_time")

        elif search_type == "unread":
            inbox_obj = request.user.inboxinfopeople_set.filter(readed='unread', deleted='b',
                                                                inbox_id__is_draft=False).order_by("-create_time")

        else:
            inbox_obj = request.user.inboxinfopeople_set.filter(readed='read', deleted='b',
                                                                inbox_id__is_draft=False).order_by("-create_time")

        inbox_li = []
        for i in inbox_obj:
            item = {}
            item['message_id'] = i.inbox_id.id
            item['sender_name'] = i.inbox_id.proposer.real_name
            item['sender'] = i.inbox_id.proposer.job_number
            item['title'] = i.inbox_id.title
            item['read'] = False if i.readed == 'unread' else True
            item['content'] = i.inbox_id.content.replace("%26nbsp;", '')
            item['plain_text'] = i.inbox_id.plain_text
            item['create_time'] = i.inbox_id.create_time.strftime("%Y-%m-%d %H:%M")
            item['ids'] = str(uuid.uuid4())
            item['deleted_id'] = i.id
            inbox_li.append(item)

        page_number = inbox_obj.count() // 15 if inbox_obj.count() % 15 == 0 else (inbox_obj.count() // 15) + 1
        cunt_page = int(page)
        last_page = int(page) - 1
        next_page = int(page) + 1

        if search:
            returnDict = {'code': 200, 'message': '获取成功',
                          'data': {"inbox_li": inbox_li[(int(page) - 1) * 15:int(page) * 15],
                                   "page_number": page_number,
                                   "cunt_page": cunt_page, "last_page": last_page, "next_page": next_page}}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")

        return render(request, 'correspondence/deleted.html',
                      {'realname': real_name, 'position': position, 'department': department,
                       'inbox_li': inbox_li[(int(page) - 1) * 15:int(page) * 15], "page_number": page_number,
                       "cunt_page": cunt_page, "last_page": last_page, "next_page": next_page})

# 发送
class SendMessageView(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
            position = request.user.post
            department = request.user.company.name
        except:
            return redirect("/")

        message_id = request.GET.get('message_id', None)
        if message_id:
            message_obj = InboxInfo.objects.get(id=message_id)
            recipient = ",".join([i.recipient_name.replace("<", "(").replace(">", ")") for i in message_obj.inboxinfopeople_set.all()])

            item = {}
            item['message_id'] = message_obj.id
            item['unique'] = message_obj.accessory_uuid
            item['sender_name'] = message_obj.proposer.real_name
            item['recipient'] = recipient
            item['title'] = message_obj.title
            item['message_content'] = message_obj.content.replace("%26nbsp;", '')
            item['create_time'] = message_obj.create_time.strftime("%Y-%m-%d %H:%M:%S")
            enclosure = Topicsattachments.objects.filter(topics_number=message_obj.accessory_uuid)
            item['file_path_text'] = [{"file_path": str(enclosure[i].file_path), "file_name": enclosure[i].file_name, "pdf_path": enclosure[i].pdf_path, "create_time": enclosure[i].create_time.strftime("%Y-%m-%d %H:%M:%S"),
                                     "id": enclosure[i].id, "uploader_user": enclosure[i].uploader_user.real_name,"file_size": enclosure[i].file_size,  "serial": i+1, "download_path": f"/announcements/file_download?file_path={os.getcwd()}/media/{str(enclosure[i].file_path)}" if (
                                    'static' not in str(enclosure[i].file_path)) and ('media' not in str(enclosure[i].file_path)) else f"/announcements/file_download?file_path={os.getcwd()}{str(enclosure[i].file_path)}"}
                                      for i in range(enclosure.count())]

            return render(request, 'correspondence/write.html', {'realname': real_name, 'position': position, 'department': department, 'message_id': item['message_id'],
                           'title': item['title'], 'recipient': item['recipient'], 'message_content': item['message_content'], 'file_list': item['file_path_text'], "unique": item['unique']})


        return render(request, 'correspondence/write.html', {'realname': real_name, 'position': position, 'department': department, 'unique': uuid.uuid4()})

    # 发送信息
    def post(self, request):
        recipient = request.POST.get('recipient', None)         # 收件人
        message_content = request.POST.get('content', None)  # 邮件内容
        title = request.POST.get('title', None)              # 标题
        is_draft = request.POST.get('is_draft', None)  # 是否为草稿
        plain_text = request.POST.get('plain_text', None)  # 邮件纯文本
        message_id = request.POST.get('message_id', None)  # 草稿邮件
        unique = request.POST.get('unique', None)  # 附件唯一标识
        recipient_li_1 = [t.strip() for t in recipient.split(',')]

        send_people_leave = request.user.level
        send_people_comple_style = request.user.company.is_functional
        if not send_people_comple_style:
            if send_people_leave == "6" and len(recipient_li_1) > 1:
                returnDict = {"code": 400, "message": "对不起，当前帐号无法群发邮件！请联系管理员。", "data": []}
                return HttpResponse(json.dumps(returnDict), content_type="application/json")
            if len(recipient_li_1) == 1:
                for i in recipient_li_1:
                    if '(' in i:
                        user_obj = User.objects.get(job_number=re.findall("\((.*?)\)", i, re.S)[0])
                        if user_obj.level in ["1", "2"]:
                            returnDict = {"code": 400, "message": "对不起，当前帐号无法直接发送邮件给院领导！请联系管理员。", "data": []}
                            return HttpResponse(json.dumps(returnDict), content_type="application/json")

        if message_id:
            # try:
            print(message_id)
            later_obj = InboxInfo.objects.get(id=int(message_id.replace("#", "")))
            later_obj.content = message_content
            later_obj.plain_text = plain_text
            later_obj.accessory_uuid = unique
            later_obj.title = title
            later_obj.is_draft = is_draft
            later_obj.save()

            later_obj.inboxinfopeople_set.all().delete()
            for i in recipient_li_1:
                if '(' in i:
                    user_obj = User.objects.get(job_number=re.findall("\((.*?)\)", i, re.S)[0])
                    InboxInfoPeople.objects.create(
                        inbox_id=later_obj,
                        recipient=user_obj,
                        recipient_name=f"{user_obj.real_name}<{user_obj.job_number}>"
                    )
            # except Exception as e:
            #     print(e)
            #     returnDict = {"code": 400, "message": "插入失败", "data": str(e)}
            #     return HttpResponse(json.dumps(returnDict), content_type="application/json")
        else:
            try:
                InboxInfo_obj = InboxInfo.objects.create(
                    content=message_content,
                    plain_text=plain_text,
                    title=title,
                    accessory_uuid=unique,
                    is_draft=True if is_draft == 'True' else False,
                    proposer=request.user
                )
                for i in recipient_li_1:
                    if '(' in i:
                        user_obj = User.objects.get(job_number=re.findall("\((.*?)\)", i, re.S)[0])
                        InboxInfoPeople.objects.create(
                            inbox_id=InboxInfo_obj,
                            recipient=user_obj,
                            recipient_name=f"{user_obj.real_name}<{user_obj.job_number}>"
                        )
            except Exception as e:
                print(e)
                returnDict = {"code": 400, "message": "插入失败", "data": str(e)}
                return HttpResponse(json.dumps(returnDict), content_type="application/json")
        returnDict = {"code": 200, "message": "发送成功"}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

def index(request):
    return render(request, 'correspondence/index.html')

def room(request, room_name):
    print(room_name)
    return render(request, 'correspondence/room.html', {
        "room_name": room_name
    })


# 查询聊天记录
class query_records(View):
    def post(self, request):
        from_people = request.POST.get('from_people', None)  # 发信人
        roomName = request.POST.get('roomName', None)  # 收信人

        try:
            data_list = []
            room_user = User.objects.get(job_number=roomName)
            from_user = User.objects.get(job_number=from_people)
            chat_obj = chatting_records.objects.filter(Q(from_user=User.objects.get(job_number=from_people), to_user=User.objects.get(job_number=roomName)) |
                                                       Q(from_user=User.objects.get(job_number=roomName), to_user=User.objects.get(job_number=from_people))
                                                       ).order_by("create_time")

            if request.user == room_user:
                to_user_img = '/media/' + str(from_user.head_portrait)
                my_img = '/media/' + str(request.user.head_portrait)
            else:
                my_img = '/media/' + str(from_user.head_portrait)
                to_user_img = '/media/' + str(request.user.head_portrait)

            for i in chat_obj:
                one_dict = json.loads(i.content)
                data_list.append(one_dict)
        except:
            to_user_img = ''
            my_img = ''
            data_list = []
        returnDict = {"code": 200, "message": "发送成功", "data": data_list, 'my_img': my_img, 'to_user_img': to_user_img}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

# 聊天消息提醒
class message_reminder(View):
    def post(self, request):
        chattin_obj = chatting_records.objects.filter(Q(from_user=request.user) | Q(to_user=request.user.job_number)).order_by("-update_time")
        read_dict = {}
        creat_litag_dict = {}
        for i in chattin_obj:
            json_count = json.loads(i.content)
            flag = "false"
            for j in json_count:
                if j["read"] == 0 and str(j["to_user"]) == str(request.user.job_number):
                    flag = "true"
                    break
            read_dict[i.room_id] = flag
            creat_litag_dict[i.room_id] = {"picture_path": json_count[0]["from_img"], "people_name": json_count[0]["from_name"], "job_number": json_count[0]["from"]}
        returnDict = {"code": 200, "message": "发送成功", "read_dict": read_dict, "creat_litag_dict": creat_litag_dict}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

# 消息通知
class message_notice(View):
    def post(self, request):
        chattin_obj = chatting_records.objects.filter(Q(from_user=request.user) | Q(to_user=request.user.job_number)).order_by("-update_time")
        chart_number = 0
        for i in chattin_obj:
            json_count = json.loads(i.content)
            for j in json_count:
                if j["read"] == 0 and str(j["to_user"]) == str(request.user.job_number):
                    chart_number += 1

        group_number = 0
        group_obj = request.user.chart_group_user.all()
        for t in group_obj:
            try:
                content_data = json.loads(t.content)
                for k in content_data:
                    if k["to_user"][request.user.job_number]["read"] == 0:
                        print(t.group_name)
                        group_number += 1
            except:
                pass
        chart_number += group_number
        returnDict = {"code": 200, "message": "发送成功", "chart_number": chart_number}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


# 消息标记已读
class MarkRead(View):
    def post(self, request):
        room_id = request.POST.get("room_id", None)
        from_people = request.POST.get("from_people", None)
        chattin_obj = chatting_records.objects.get(room_id=room_id)

        json_count = json.loads(chattin_obj.content)
        read_list = []
        for j in json_count:
            if str(j["to_user"]) == str(request.user.job_number):
                j["read"] = 1
            read_list.append(j)
        chattin_obj.content = json.dumps(read_list)
        chattin_obj.save()
        returnDict = {"code": 200, "message": "发送成功"}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class reply_email(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
            position = request.user.post
            department = request.user.company.name
        except:
            return redirect("/")

        message_id = request.GET.get('id', 11)
        message_obj = InboxInfo.objects.get(id=message_id)

        item = {}
        item['message_id'] = message_obj.id
        item['unique'] = message_obj.accessory_uuid
        item['sender_name'] = message_obj.proposer.real_name
        item['recipient'] = message_obj.proposer.real_name + f"({message_obj.proposer.job_number})"
        item['title'] = f"回复：'{message_obj.title}'"
        item['message_content'] = "<div style='background: #f2f2f2;'><p>----------原始信件----------</p>"+message_obj.content.replace("%26nbsp;", '')+"</div>"
        item['create_time'] = message_obj.create_time.strftime("%Y-%m-%d %H:%M:%S")

        return render(request, 'correspondence/write.html', {'reply_flag': 'true','realname': real_name, 'position': position, 'department': department, 'message_id': item['message_id'],
                       'title': item['title'], 'recipient': item['recipient'], 'message_content': item['message_content'], "unique": uuid.uuid4()})

    # 发送信息
    def post(self, request):
        message_id = request.POST.get('id', None)         # 回信原信件ID
        textarea_footer = request.POST.get('textarea_footer', None)
        later_obj = InboxInfo.objects.get(id=int(message_id.replace("#", "")))

        message_content = f"<p>{textarea_footer}</p></br>"+"<div style='background: #f2f2f2;'><p>----------原始信件----------</p>"+later_obj.content.replace("%26nbsp;", '')+"</div>"
        plain_text = f"{textarea_footer}----------原始信件----------{later_obj.plain_text}"
        title = f"回复：'{later_obj.title}'"

        try:
            InboxInfo_obj = InboxInfo.objects.create(
                content=message_content,
                plain_text=plain_text,
                title=title,
                accessory_uuid=uuid.uuid4(),
                is_draft=False,
                proposer=request.user
            )
            InboxInfoPeople.objects.create(
                inbox_id=InboxInfo_obj,
                recipient=later_obj.proposer,
                recipient_name=f"{later_obj.proposer.real_name}<{later_obj.proposer.job_number}>"
            )

        except Exception as e:
            print(e)
            returnDict = {"code": 400, "message": "插入失败", "data": str(e)}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")
        returnDict = {"code": 200, "message": "发送成功"}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


def str2md5(str):
    m = hashlib.md5()  # 创建md5对象
    str_en = str.encode(encoding='utf-8')  # str必须先encode
    m.update(str_en)  # 传入字符串并加密
    str_md5 = m.hexdigest()  # 将MD5 hash值转换为16进制数字字符串
    return str_md5

class CreateGroup(View):
    def post(self, request):
        group_name = request.POST.get("group_name", '')
        user_list = json.loads(request.POST.get("choose_list", ''))

        if not group_name:
            returnDict = {"code": 400, "message": "请确定群组名称！"}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")
        if not user_list:
            returnDict = {"code": 400, "message": "请选择群组聊天人员！"}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")

        obj = ChatGroups.objects.create(room_id=str2md5(''.join(user_list)), group_name=group_name)
        obj.group_user.add(request.user)
        for i in user_list:
            obj.group_user.add(User.objects.get(job_number=i))
        returnDict = {"code": 200, "message": "创建成功！"}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")